<template>
  <el-dialog
    :title="title"
    :visible.sync="innerVisible"
    width="1200px"
    @close="handleCancel"
  >
    <el-button
      class="mb-2"
      type="primary"
      @click="handleAdd"
    >
      新增
    </el-button>
    <el-table
      :data="tableData"
      :header-cell-style="{
        background: '#F2F6FB',
        color: ' #6B767D'
      }"
      height="500px"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        label="企业名称"
        prop="name"
        width="250"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.name"
            filterable
            allow-create
            placeholder="请选择"
            style="width: 230px"
            @change="
              (value) =>
                onEnterpriseChanage(value, scope.row)
            "
          >
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.pkid"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="统一社会信用代码"
        prop="socialCode"
        width="230"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.socialCode"
            placeholder="请输入"
            style="width: 200px"
            :disabled="
              getIsSocialCodeDisabled(scope.row.name)
            "
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="入驻楼层" prop="occupancyNum">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.occupancyNum"
            placeholder="请输入"
            type="number"
            style="width: 160px"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column
        label="入驻面积（平方米）"
        prop="occupancyArea"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.occupancyArea"
            placeholder="请输入"
            type="number"
            style="width: 160px"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column
        label="入驻时间"
        prop="occupancyTime"
      >
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.occupancyTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 160px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template slot-scope="scope">
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            style="color: #ff5b5b; font-weight: 400"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  assetsOptions
  // responseOptions
} from '@/utils/project/data'
import {
  enterpriseInfoQuery,
  postBatchUpdateEnterprise
} from '@/api/dataManagement'
import { RESPONSE_DEPT_NAME } from '@/utils/project/data'
import { findPathByValue } from '@/utils/tree'

export default {
  name: 'ProgressDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: '入驻企业'
    },
    dataSource: {
      type: String,
      default: '产业载体'
    },
    buildId: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      innerVisible: false,
      tableData: [],
      enterpriseOptions: []
    }
  },
  computed: {
    assetsOptions() {
      return assetsOptions
    }
  },
  async mounted() {
    this.getEnterpriseOptions()
  },
  watch: {
    visible(val) {
      this.innerVisible = val
    },
    innerVisible(val) {
      this.$emit('update:visible', val)
    },
    list(val) {
      this.tableData = val || []
    }
  },
  methods: {
    // 表格高亮
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    getEnterpriseOptions() {
      enterpriseInfoQuery({
        pageIndex: 1,
        pageSize: 999
      }).then((res) => {
        if (res.success) {
          this.enterpriseOptions = res.data.list.map(
            (item) => {
              return {
                ...item,
                label: item.name,
                value: item.name
              }
            }
          )
        }
      })
    },
    getIsSocialCodeDisabled(name) {
      return this.enterpriseOptions.some(
        (item) => item.name === name
      )
    },
    onEnterpriseChanage(name, row) {
      console.log('onEnterpriseChanage name', name)
      console.log('onEnterpriseChanage row', row)
      const one = this.enterpriseOptions.find(
        (item) => item.name === name
      )
      console.log('onEnterpriseChanage one', one)
      if (one) {
        row.pkid = one.pkid
        row.name = one.name
        row.socialCode = one.socialCode
        row.occupancyArea = one.occupancyArea
        row.occupancyNum = one.occupancyNum
        row.occupancyTime = one.occupancyTime
      }
    },
    handleAdd() {
      this.tableData.push({
        pkid: '',
        name: '',
        socialCode: '',
        occupancyNum: '',
        occupancyArea: '',
        occupancyTime: '',
        buildId: this.buildId,
        dataSource: this.dataSource,
        department: localStorage.getItem('deptName')
      })
    },
    handleDelete(row) {
      console.log('delete row', row)
      if (row.pkid) {
        postBatchUpdateEnterprise([
          {
            ...row,
            buildId: '',
            occupancyNum: '',
            occupancyArea: '',
            occupancyTime: ''
          }
        ]).then((res) => {
          this.$message.success('删除成功')
          this.tableData = this.tableData.filter(
            (e) => e !== row
          )
        })
      } else {
        this.tableData = this.tableData.filter(
          (e) => e !== row
        )
      }
    },

    handleCancel() {
      this.$emit('update:visible', false) // 父组件控制 visible
    },
    handleConfirm() {
      // this.$refs.formRef.validate((valid) => {
      //   if (valid) {
      //     // if (this.form.unit) {
      //     //   this.form.unit = this.form.unit.join(',')
      //     // } else {
      //     //   this.form.unit = ''
      //     // }
      //     this.$emit('confirm', { ...this.form })
      //     this.handleCancel()
      //   }
      // })
      console.log('save table', this.tableData)
      const err = this.tableData.find(
        (e) => !e.name || !e.socialCode
      )
      if (err) {
        this.$message.error(
          '企业名称和统一社会信用代码不能为空！'
        )
        return
      }
      postBatchUpdateEnterprise(this.tableData).then(
        (res) => {
          if (res.success) {
            this.$message.success('保存成功')
            this.$emit('confirm', this.tableData)
            this.handleCancel()
            console.log('handleConfirm', this.tableData)
          } else {
            this.$message.error(res.message || '保存失败')
          }
        }
      )
      // this.handleCancel()
    },

    validateEnterpriseContent() {
      if (this.form.enterpriseContent) {
        const correctedValue =
          this.form.enterpriseContent.replace(/，/g, ',')

        if (
          correctedValue !== this.form.enterpriseContent
        ) {
          this.form.enterpriseContent = correctedValue
          this.$message.info(
            '已自动将中文逗号替换为英文逗号'
          )
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/dialog.scss';
// ::v-deep .el-input__inner {
//   width: 320px !important;
// }
// ::v-deep .el-textarea__inner {
//   width: 320px !important;
// }
.mb-2 {
  margin-bottom: 16px;
}
::v-deep .el-input__inner {
  width: 100% !important;
}
::v-deep .el-input__icon {
  line-height: 34px;
}
</style>
